const XLSX = require("xlsx");
const fs = require("fs");

function outputJson() {
  // 读取 Excel 文件
  const workbook = XLSX.readFile("./translations.xlsx");
  const sheetName = workbook.SheetNames[0];
  const worksheet = workbook.Sheets[sheetName];
  const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

  // 获取表头作为文件名
  const headers = data[0].slice(1);

  // 确保 file 文件夹存在
  const langDir = "./file";
  if (!fs.existsSync(langDir)) {
    fs.mkdirSync(langDir, { recursive: true });
  }

  // 处理数据，第一列作为 key，后面四列作为值
  for (let i = 1; i < headers.length + 1; i++) {
    const output = {};
    for (let j = 1; j < data.length; j++) {
      const key = data[j][0];
      const value = data[j][i];
      output[key] = value;
    }

    // 输出文件到 lang 文件夹
    const fileName = `${langDir}/${headers[i - 1]}.json`;
    fs.writeFileSync(fileName, JSON.stringify(output, null, 2));
    console.log(`File ${fileName} created successfully.`);
  }
}

module.exports = outputJson;
